import React from "react";
import { Form, Modal, Select, Switch, Radio } from "antd";
import { openNotificationWithIcon } from "utils/comm";
import { prefixedAction } from "../models/noticeModel";

const { Option } = Select;
const RadioGroup = Radio.Group;

export const NoticeTypeFlow = 'FLOW';
export const NoticeTypeNode = 'NODE';
export const renderTypeMap = {
  [NoticeTypeFlow]: '流程通知',
  [NoticeTypeNode]: '节点任务通知',
};

const formItemLayout1 = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};

// // 流程通知主题mock
// const flowNoticeThemes = [
//   { code: 1, name: '流程预警通知' },
//   { code: 2, name: '流程超时通知' },
// ];

// // 节点任务通知通知主题mock
// const nodeNoticeThemes = [
//   { code: 3, name: '任务转办通知' },
//   { code: 4, name: '任务超时通知' },
//   { code: 5, name: '任务加签通知' },
//   { code: 6, name: '任务催办通知' },
//   { code: 7, name: '任务预警通知' },
//   { code: 8, name: '任务开始通知' },
//   { code: 9, name: '任务撤回通知' },
//   { code: 10, name: '任务完成通知' },
//   { code: 11, name: '任务签收通知' },
// ]
@Form.create()
class CreateForm extends React.Component {
  constructor(props) {
    super(props);
    this.openNotificationWithIcon = openNotificationWithIcon.bind(this);
    this.inputRef = React.createRef();
    this.textareaRef = React.createRef();
    const { data: { messageThemCode = '', type = '' } = {} } = props;
    this.state = {
      messageThemeCode: messageThemCode,
      type,
    }
  }

  componentDidMount() {
    const { form } = this.props;
    const { type } = this.state;
    if (!type) {
      form.setFieldsValue({ type: NoticeTypeFlow });
      this.setState({ type: NoticeTypeFlow });
    }
  }

  handleOk = (e) => {
    if (e && e.preventDefault) e.preventDefault();
    const { form, dispatch, data, msgThemeTypeList, noticeThemeTypeList } = this.props;

    form.validateFields((err, values) => {
      if (err) {
        return;
      }

      let type = prefixedAction("addNotice");
      const params = {  ...values };
      if (data) {
        type = prefixedAction("editNotice");
        params.id = data.id;
      }
      
      
      for(const noticeThemeType of noticeThemeTypeList) {
        if (noticeThemeType.key === params.noticeThemCode) {
          params.noticeThemName = noticeThemeType.value;
          break;
        }
      }

      params.status = params.status ? 1 : 0;

      for(const msgThemeType of msgThemeTypeList) {
        if (msgThemeType.templateId === params.messageThemCode) {
          params.messageThemName = msgThemeType.templateName;
          break;
        }
      }

      dispatch({ type, payload: params }).then((resp) => {
        const { errCode, errortext } = resp;
        if (errCode === 0) {
          this.handleCancel(true);
          form.resetFields();
          this.openNotificationWithIcon("success", "", errortext || "操作成功");
        } else {
          this.openNotificationWithIcon("warning", "", errortext || "操作失败");
        }
      });
    });
  };

  handleCancel = (isQuery = false) => {
    const { handleCreateVisible } = this.props;
    handleCreateVisible(false, "", isQuery);
  };

  onRadioChange = (e) => {
    const { form } = this.props;
    form.setFieldsValue({ noticeThemCode: undefined, type: e.target.value });
    this.setState({ type: e.target.value });
  };

  render() {
    const { form, visible, confirmLoading, data = {}, title = "", noticeThemeTypeList, msgThemeTypeList } = this.props;
    const record = data || {};
    const { getFieldDecorator } = form;
    const { messageThemeCode, type } = this.state;
    
    return (
      <Modal
        title={title}
        visible={visible}
        onOk={this.handleOk}
        onCancel={() => this.handleCancel()}
        width="582px"
        centered
        confirmLoading={confirmLoading}
      >
        <Form>
          <Form.Item label="通知类型" {...formItemLayout1}>
            {getFieldDecorator('type', {
              rules: [{ required: true, message: '请选择通知类型' }],
              initialValue: record ? record.type : NoticeTypeFlow,
            })(
              <RadioGroup onChange={this.onRadioChange}>
                <Radio value={NoticeTypeFlow}>流程通知</Radio>
                <Radio value={NoticeTypeNode}>节点任务通知</Radio>
              </RadioGroup>,
            )}
          </Form.Item>
          <Form.Item label="通知主题" {...formItemLayout1}>
            {getFieldDecorator('noticeThemCode', {
              initialValue: record.noticeThemCode,
              rules: [{ required: true, message: '请选择通知主题' }],
            })(
              <Select placeholder="请选择通知主题">
                {Array.isArray(noticeThemeTypeList) &&
                  noticeThemeTypeList.filter(({ type: _type}) => type === _type).map((item = {}) => (
                    <Option key={item.key} value={item.key}>
                      {item.value}
                    </Option>
                  ))}
              </Select>,
            )}
          </Form.Item>
          <Form.Item label="消息主题" {...formItemLayout1}>
            {getFieldDecorator('messageThemCode', {
              initialValue: record.messageThemCode,
              rules: [{ required: true, message: '请选择消息主题' }],
            })(
              <Select placeholder="请选择消息主题" onChange={(value) => this.setState({ messageThemeCode: value })}>
                {Array.isArray(msgThemeTypeList) &&
                  msgThemeTypeList.map((item = {}) => (
                    <Option key={item.templateId} value={item.templateId}>
                      {item.templateName}
                    </Option>
                  ))}
              </Select>,
            )}
          </Form.Item>
          <Form.Item label="消息主题编码" {...formItemLayout1}>
            <span>{messageThemeCode}</span>
          </Form.Item>
          <Form.Item label="开启状态" {...formItemLayout1}>
            {getFieldDecorator("status", {
              initialValue: Boolean(Number(record.status)) || false,
              rules: [{ required: true, message: "" }],
              valuePropName: 'checked',
            })(
              <Switch />
                // checked={Boolean(Number(status))}
                // onChange={() => this.handleSwitchChange(status)}
            )}
          </Form.Item>
        </Form>
      </Modal>
    );
  }
}

export default CreateForm;
